/**
 * 
 */
package com.apache.portal.weixin.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.apache.tools.StrUtil;

/**
 * 公共action
 */
@SuppressWarnings("serial")
public abstract class BaseAction extends HttpServlet {

	protected Logger log = Logger.getLogger(this.getClass().getName());

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {
		String methodKey = StrUtil.doNull(request.getParameter("method"), "execute");
		if (StrUtil.isNull(methodKey)) {
			execute(request, response);
		} else {
			try {
				Method qm = this.getClass().getMethod(methodKey,
						new Class[] { HttpServletRequest.class, HttpServletResponse.class });
				qm.invoke(this, request, response);
			} catch (Exception e) {
				log.error("执行方法[" + methodKey + "]时出错：", e);
			}
		}
	}

	/**
	 * 输出json数据
	 * @param json
	 * @param response
	 * @throws IOException
	 */
	protected void outputJson(String json, HttpServletResponse response) throws IOException {
		if (StrUtil.isNotNull(json)) {
			response.setContentType("text/html;charset=UTF-8");
			PrintWriter out = response.getWriter();
			out.print(json);
			out.flush();
			out.close();
		}
	}

	/**
	  * description: 默认方法(当没有传operation(即调用方法名)参数时会自动调用此方法);
	  * @return
	 */
	public abstract void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException;
}
